package cn.edu.cdu;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.*;
import java.util.Enumeration;

public class GameMain extends JFrame implements ActionListener{
    //socket初始化
    private ServerSocket server=null;
    private Socket client= null;
    //输入输出流
    private DataInputStream din=null;
    private DataOutputStream dou=null;
    //对手信息
    private Opponent opponent;
    //面板各种组件
    private ChessBoard chessboard;
    private Welcome welcome;
    private JButton createGame,joinGame;
    private JPanel mainWin=new JPanel();

    public GameMain() {
        setTitle("五子棋");
        setResizable(false);
        setSize(800,700);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setVisible(true);
        //初始化欢迎面板
        createGame=new JButton("创建游戏");
        createGame.addActionListener(this);
        joinGame=new JButton("加入游戏");
        joinGame.addActionListener(this);
        welcome=new Welcome(createGame,joinGame);
        welcome.add(createGame);
        welcome.add(joinGame);
        //设置为卡片布局
        mainWin.setLayout(new CardLayout());
        mainWin.add(welcome,"欢迎");
        mainWin.setVisible(true);
        this.add(mainWin);
        this.setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        final CardLayout layout= (CardLayout) mainWin.getLayout();
        if(e.getSource()==joinGame){
            String name=JOptionPane.showInputDialog(this,"请输入游戏昵称:","456");
            if(name!=null&&!name.equals("")){
                String ip=JOptionPane.showInputDialog(this,"请输入游戏ip地址","127.0.0.1");
                if(ip!=null&&!ip.equals("")){
                    try {
                        //连接对方游戏
                        try {
                            client = new Socket(ip,5566);
                        } catch (Exception e1) {
                            JOptionPane.showMessageDialog(this,"连接超时,该地址可能有误！","连接超时",JOptionPane.WARNING_MESSAGE);
                        }
                        din=new DataInputStream(client.getInputStream());
                        dou=new DataOutputStream(client.getOutputStream());
                        System.out.println("连接成功");
                        //发送自己的信息
                        dou.writeUTF(name);
                        dou.writeUTF(getIp());
                        //接受对手信息
                        String opponentName=din.readUTF();
                        String localIp=din.readUTF();
                        opponent=new Opponent(opponentName,localIp,true);
                        System.out.println(opponent.getName());
                        System.out.println(opponent.getIp());
                        //初始化棋盘面板
                        chessboard=new ChessBoard(din,dou,opponent);
                        mainWin.add(chessboard,"游戏");
                        layout.show(mainWin,"游戏");
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            }
        }else if(e.getSource()==createGame){
            new Thread(new Runnable(){
                @Override
                public void run() {
                    try {
                        //接受姓名
                        String name=JOptionPane.showInputDialog("请输入游戏昵称:","123");
                        if(name!=null&&!name.equals("")){
                            try {
                                server=new ServerSocket(5566);
                            } catch (IOException e1) {
                                e1.printStackTrace();
                                server.close();
                                server=new ServerSocket(5566);
                                System.out.println("重置成功");
                            }
                            System.out.println("房间已创建，正在等待加入");
                            //显示提示
                            welcome.getPrompt().setVisible(true);
                            welcome.setIpAdress(getIp());
                            welcome.getIp().setVisible(true);
                            //等待连接
                            client=server.accept();
                            din=new DataInputStream(client.getInputStream());
                            dou=new DataOutputStream(client.getOutputStream());
                            //发送自己信息
                            dou.writeUTF(name);
                            dou.writeUTF(getIp());
                            System.out.println("已连接");
                            //接受对手信息
                            String opponentName=din.readUTF();
                            String localIp=din.readUTF();
                            opponent=new Opponent(opponentName,localIp,false);
                            System.out.println(opponent.getName());
                            System.out.println(opponent.getIp());
                            //初始化棋盘面板
                            chessboard=new ChessBoard(din,dou,opponent);
                            mainWin.add(chessboard,"游戏");
                            //开始游戏
                            layout.show(mainWin,"游戏");
                            welcome.getPrompt().setVisible(false);
                            welcome.getIp().setVisible(false);
                        }
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            }).start();
        }
    }

    /**
     * 获取本地Ip
     * @return Ip地址
     */
    private String getIp(){
        try {
            //筛选本地的IP地址，并获取
            Enumeration<NetworkInterface> interfaces=NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()){
                NetworkInterface ni=interfaces.nextElement();
                Enumeration<InetAddress> address=ni.getInetAddresses();
                while (address.hasMoreElements()){
                    InetAddress nextElement=address.nextElement();
                    String s=nextElement.getHostAddress();
                    if(s.contains("192.168")){
                        return s;
                    }
                }
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return "";
    }
    public static void main(String[] args) {
        GameMain game=new GameMain();
    }
}
